package com.yoda.youdianda.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yoda.youdianda.common.ErrorResult;
import com.yoda.youdianda.common.R;
import com.yoda.youdianda.domain.SysRole;
import com.yoda.youdianda.domain.SysUser;
import com.yoda.youdianda.dto.PageDto;
import com.yoda.youdianda.dto.SysUserDto;
import com.yoda.youdianda.dto.UserDto;
import com.yoda.youdianda.dto.UserLoginFrontDto;
import com.yoda.youdianda.exception.BusinessException;
import com.yoda.youdianda.mapper.SysUserMapper;
import com.yoda.youdianda.service.SysRoleService;
import com.yoda.youdianda.service.SystemUserService;
import com.yoda.youdianda.util.JwtUtils;
import com.yoda.youdianda.util.Util;
import com.yoda.youdianda.vo.SysUserVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shawn
 * @date 2022年 11月 13日 0:35
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SystemUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    SystemUserService systemUserService;
    @Autowired
    SysRoleService roleService;
    @Override
    public SysUser selectUserByLoginName(String login_name){
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLoginName,login_name);
        wrapper.eq(SysUser::getDelFlag,0);
        return sysUserMapper.selectOne(wrapper);
    }


    public SysUser selectUserById(String userId) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getDelFlag,0);
        return sysUserMapper.selectById(userId);
    }

    @Override
    public R<String> add(UserDto dto) {
        //将接受的数据转为SysUser类型
        SysUser user = new SysUser();
        BeanUtils.copyProperties(dto,user);
        user.setLoginName(dto.getLogin_name());
        user.setLoginDate(new Date());
        user.setRoleId(JSON.toJSONString(dto.getRole_id()));
        user.setId(UUID.randomUUID().toString());
        user.setDefaultData("1");

        String password = dto.getPassword();

        password = DigestUtils.md5DigestAsHex(password.getBytes());

        user.setPassword(password);


        int count = sysUserMapper.insert(user);

        return count>0?R.success("添加成功!"):R.error("添加失败!");
    }

    @Override
    public void updateUser(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public Integer countUsers() {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getDelFlag,0);
        return sysUserMapper.selectCount(wrapper);
    }

    @Override
    public PageDto getList(String loginName, String status, String phone, int page, int limit) {

        Page<SysUser> sysUserPage = new Page<>(page,limit);

        LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.like(StringUtils.isNotEmpty(loginName), SysUser::getLoginName, loginName);
        userLambdaQueryWrapper.eq(StringUtils.isNotEmpty(status), SysUser::getStatus, status);
        userLambdaQueryWrapper.like(StringUtils.isNotEmpty(phone), SysUser::getPhone, phone);
        userLambdaQueryWrapper.eq(SysUser::getDelFlag, "0");
        this.page(sysUserPage, userLambdaQueryWrapper);

        PageDto pageDto = new PageDto();
        BeanUtils.copyProperties(sysUserPage, pageDto, "records");

        List<SysUser> records = sysUserPage.getRecords();

        List<SysUserDto> userDtos = records.stream().map(item -> {

            SysUserDto userDto = new SysUserDto();

            BeanUtils.copyProperties(item, userDto);

            List<String> roleName = new ArrayList<>();

            String roleIds = item.getRoleId();

            List<String> roleId = Util.roleIdTransform(roleIds);

            LambdaQueryWrapper<SysRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
            roleLambdaQueryWrapper.in(SysRole::getId, roleId);

            List<SysRole> sysRoles = roleService.list(roleLambdaQueryWrapper);

            for (SysRole sysRole : sysRoles) {
                roleName.add(sysRole.getName());
            }

            userDto.setRoleName(roleName);

            return userDto;

        }).collect(Collectors.toList());

        pageDto.setRecords(userDtos);

        return pageDto;
    }


    @Override
    public R<String> del(String id) {
        LambdaUpdateWrapper<SysUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(SysUser::getDelFlag, "1");
        wrapper.eq(SysUser::getId, id);
        systemUserService.update(wrapper);
        return R.success("");
    }

    @Override
    public R<String> udp(UserDto dto) {
        String password = dto.getPassword();
        //如果密码不为空,就讲密码进行MD5加密
        if (password != null) {
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            dto.setPassword(password);
        }
        //将接受的数据转为SysUse形式
        SysUser user = new SysUser();
        BeanUtils.copyProperties(dto,user);
        user.setRoleId(JSON.toJSONString(dto.getRole_id()));

        systemUserService.updateUser(user);


        return R.success("修改成功");
    }

    //数据回显
    @Override
    public R<SysUserVo> row(String id) {
        //前端传回的数据是SysUser形式
        SysUserVo sysUserVo = new SysUserVo();
        SysUser sysUser = systemUserService.selectUserById(id);
        sysUser.setPassword(null);
        String roleIds = sysUser.getRoleId();
        List<String> roleId = JSON.parseObject(roleIds, List.class);
        //将数据转为SysUserVo形式返回
        BeanUtils.copyProperties(sysUser, sysUserVo);
        sysUserVo.setRoleId(roleId);
        return R.success(sysUserVo);
    }
}
